package com.chuangfeng.framework.core.service.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;

import com.chuangfeng.framework.core.common.page.Pagination;
import com.chuangfeng.framework.core.dao.BaseDao;
import com.chuangfeng.framework.core.exception.ServiceException;
import com.chuangfeng.framework.core.service.BaseMng;

/**
 * 
 * 业务逻辑层祖先类。
 * 所有的业务逻辑类继承该类，该类主要通过注入DAO实现对数据库持久层的业务调用。
 * @author xiedy
 *
 * @param <T>
 */
public class BaseMngImpl<T extends Serializable> implements BaseMng<T> {

	protected final Logger logger = Logger.getLogger(this.getClass());
	
	private BaseDao<T> dao;
	
	public BaseDao<T> getDao() {
		return dao;
	}
    
	public void setDao(BaseDao<T> baseDao) {
		this.dao = baseDao;
	}
	
	
	public void add(T entity) {
		this.getDao().save(entity);
		
	}

	public void delete(T entity) {
		this.getDao().remove(entity);
		
	}

	public void deleteById(Serializable id) {
		this.getDao().removeById(id);
	}

	public void deleteMulByIds(Serializable[] ids) {
		if (ids != null && ids.length > 0) {
			for (Serializable id : ids) {
				this.deleteById(id);
			}
		}
	}
	
	public void deleteMulByIds(List<Serializable> ids){
		this.getDao().removeAllByIds(ids);
	}

	public List<T> findAll() {
		return this.getDao().getAll();
	}

	public List<T> findByHql(String hql) {
		return  this.getDao().find(hql);
	}

	public List<Map> findBySql(String sql) {
		return this.getDao().queryForList(sql);
	}
	
	public T update(T entity) {
		return this.getDao().update(entity);
	}

	public T saveAndRefresh(T entity) {
		this.add(entity);
		this.getDao().refresh(entity);
		return entity;
	}

	public T get(Serializable id) {
		return this.dao.get(id);
	}

	public T load(Serializable id) {
		return this.dao.load(id);
	}

	public T merge(T entity) {
		return this.dao.merge(entity);
	}

	public T saveOrUpdate(T entity) {
		return this.dao.saveOrUpdate(entity);
	}

	public Pagination searchPaginated(String hql) {
		try{
			return this.dao.searchPaginated(hql);
		}catch(Exception e){
			logger.error(e.getMessage());
			throw new ServiceException(e.getMessage());
		}
	}

	public Pagination searchPaginated(Criteria criteria) {
		try{
			return this.dao.searchPaginated(criteria);
		}catch(Exception e){
			logger.error(e.getMessage());
			throw new ServiceException(e.getMessage());
		}
		
	}

	public String getIdName() {
		return this.dao.getIdName();
	}
	
}
